package com.push.example;

import java.io.IOException;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.push.example.model.DeviceSecureStorage;

@SuppressWarnings("serial")
public class Register extends HttpServlet {

	public static final PersistenceManagerFactory pmfInstance = JDOHelper
			.getPersistenceManagerFactory("transactions-optional");

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		String deviceId = req.getParameter("deviceId");
		String registrationId = req.getParameter("registrationId");
		String deviceName = req.getParameter("deviceName");
		if (deviceId != null && deviceId != "" && registrationId != null
				&& registrationId != "") {
			try {
				DeviceSecureStorage dev = new DeviceSecureStorage();
				dev.deviceId = deviceId;
				dev.registrationId = registrationId;
				dev.deviceName = deviceName;
				PersistenceManager pm = pmfInstance.getPersistenceManager();
				dev = pm.makePersistent(dev);
				if (dev != null) {
					resp.getWriter().println(
							"<result error='false'>OK</result>");
				} else {
					resp.getWriter().println(
							"<result error='true'>Olmadı</result>");
				}

			} catch (Exception e) {
				resp.getWriter().println(
						"<result error='true'>" + e.toString() + "</result>");
			}
		} else {
			resp.getWriter().println(
					"<result error='true'>Parametreler Yanlis</result>");
		}
	}
}
